<template>
<div @click.stop="commit(Math.floor(Math.random() * 120))" :style="{width:size+'px',height:size+'px'}" id="gau"></div>
</template>

<script lang="ts" setup>
import {EChartsType} from 'echarts/core'
import {echarts, option} from '@/plugins/modules/echarts'
import {nextTick, onMounted, ref, watch, watchEffect} from 'vue'

interface Prop {
  colors?: [number, string][],
  value?: number,
  size?: number,
  min?: number,
  max?: number
}

const props = withDefaults(defineProps<Prop>(), {
  colors: () => [[0.3, '#67e0e3'], [0.7, '#37a2da'], [1, '#fd666d']],
  value: 0,
  size: 300,
  min: 0,
  max: 100
})

const op = Object.assign({
  series: [{
    type: 'gauge',
    startAngle: 200,
    endAngle: -20,
    splitNumber: 100,
    min: props.min,
    max: props.max,
    center: ['50%', '50%'],
    axisLine: {
      show: false,
      lineStyle: {
        width: 40,
        color: props.colors,
      }
    },
    progress: {
      width: 20,
      show: true,
      // overlap: false,
      itemStyle: {
        color: props.colors[0][1],
        // shadowColor: 'rgba(0, 0, 0, 0.5)',
        // shadowBlur: 10
      }
    },
    pointer: {
      show: false,
      icon: 'arrow',
      itemStyle: {
        color: 'inherit'
      }
    },
    axisTick: {
      distance: -50,
      length: 6,
      lineStyle: {
        color: 'auto',
        width: 2,
      }
    },
    splitLine: {
      show: false,
      distance: -30,
      length: 30,
      lineStyle: {
        color: '#fff',
        width: 4
      }
    },
    axisLabel: {
      show: false,
      color: 'inherit',
      distance: 35,
      fontSize: 18
    },
    detail: {
      valueAnimation: true,
      formatter: '{value} km/h',
      color: 'auto',
      fontSize: Math.floor(28 * props.size / 320)
    },
    data: [{
      value: props.value,
      name: 'Speed',
      title: {offsetCenter: ['0%', '-10%']},
      detail: {
        color: props.colors[0][1],
        offsetCenter: ['0%', '20%']
      }
    }]
  }]
}, option)
const chart = ref<EChartsType>()

onMounted(() => {
  let dom = document.getElementById('gau')!
  chart.value = echarts.init(dom,'dark')
  chart.value?.setOption(op)
})

const commit = (val: number) => {
  let r = val / props.max
  const colors = props.colors
  let col = colors.sort((a, b) => a[0] - b[0]).find((c) => c[0] >= r)
  let color = col !== undefined ? col[1] : colors[colors.length - 1][1]

  op.series[0].data[0].value = val
  op.series[0].progress.itemStyle.color = color
  op.series[0].data[0].detail.color = color
  chart.value?.setOption(op)
}

watch(() => props.size, () => {
  op.series[0].detail.fontSize = Math.floor(28 * props.size / 320)
  chart.value?.setOption(op)
  nextTick(chart.value?.resize)

})

defineExpose({commit})


</script>

<script lang="ts">


export default {
  name: 'Gauge'
}
</script>


<style lang="scss" scoped>

</style>
